import Vue from 'vue'
import VueRouter from 'vue-router'
import '../plugins/element.js'
import login from '../components/login.vue'
import register from '../components/register.vue'
import Home from '../views/Home.vue'
import welcome from '../components/welcome.vue'
import users from '../components/user/users.vue'
import roles from '../components/root/roles.vue'
import roots from '../components/root/roots.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/Home' },
  { path: '/login', component: login },
  { path: '/register', component: register },
  {
    path: '/Home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: welcome },
      { path: '/users', component: users },
      { path: '/roles', component: roles },
      { path: '/roots', component: roots }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 如果去login则放行
  if (to.path === '/login') return next()

  // 去其他需要登陆才能操作的界面需看有没有token，没有则登陆
  const token = window.localStorage.getItem('token')
  if (!token) {
    next('/login')
  }
  next()
})

export default router
